package com.wtp.wallpaper.utils;

import cn.hutool.cron.CronException;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronExpression;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class TaskSchedulerUtil {

    private static final ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
    private static final Map<String, ScheduledFuture<?>> scheduledFutureMap = new ConcurrentHashMap<>();

    static {
        // 配置线程池
        threadPoolTaskScheduler.setPoolSize(5);
        threadPoolTaskScheduler.setThreadNamePrefix("task-scheduler-");
        threadPoolTaskScheduler.setErrorHandler(t -> {
            System.err.println("Task error: " + t.getMessage());
        });
        threadPoolTaskScheduler.initialize();
    }

    public static void put(Runnable runnable, Trigger trigger, String id) {
        if (runnable == null || trigger == null || id == null) {
            throw new IllegalArgumentException("Arguments cannot be null");
        }
        // 取消旧任务（如果存在）
        delete(id);
        // 提交新任务
        ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(runnable, trigger);
        scheduledFutureMap.put(id, future);
    }

    public static void delete(String id) {
        if (id == null) return;
        ScheduledFuture<?> future = scheduledFutureMap.get(id);
        if (future != null) {
            if (!future.isDone()) {
                future.cancel(true); // 中断正在执行的任务
            }
            scheduledFutureMap.remove(id);
        }
    }

    public static void shutdown() {
        threadPoolTaskScheduler.shutdown();
        try {
            if (!threadPoolTaskScheduler.getScheduledThreadPoolExecutor().awaitTermination(10, TimeUnit.SECONDS)) {
                threadPoolTaskScheduler.getScheduledThreadPoolExecutor().shutdownNow();
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            threadPoolTaskScheduler.getScheduledThreadPoolExecutor().shutdownNow();
        }
    }


}